<?php
namespace app\services;

use kernel\library\Single;
use kernel\library\Error;

abstract class RESTfulAPI extends Single
{

    abstract protected function get(array $input = []);

    abstract protected function post(array $input = []);

    abstract protected function put(array $input = []);

    abstract protected function delete(array $input = []);

    public function restfull(string $event, array $input = [])
    {
        $events = ['get', 'post', 'put', 'delete', 'menu'];
        $event  = strtolower($input['_method'] ?? $event);
        if (! in_array($event, $events)) return Error::setError("不支持的请求类型", 415);
        unset($input['_token'], $input['_method']);
        
        if (isset($input['_method_']) && $input['_method_']) {
            return $this->_method_($input);
        }
        
        return $this->$event($input);
    }

    protected function result(array $data = [], $url = '')
    {
        return [
            'errorcode' => 0,
            'errormsg' => '成功',
            'data' => $data,
            'url' => $url,
            'time' => BASICS_STIME,
            'runtime' => microtime(true) - BASICS_STIME
        ];
    }

    /**
     * .获取输入
     *
     * @param array $input
     * @param string $key
     * @param string $default
     * @return string
     */
    public function input(array $input, string $key, ?string $default = null)
    {
        if ($default === null && isset($input[$key]) == false || $input[$key] === '') {
            Error::setError($key . '不能为空', 99999);
        }
        return $input[$key] ?? $default;
    }
}

